package club.kynb.mall.application.flow.user;

import club.kynb.mall.application.constant.MallResultCode;
import club.kynb.mall.application.context.AuthenticationContext;
import club.kynb.mall.application.model.model.command.AuthenticationCommand;
import club.kynb.mall.application.model.model.command.PwdAuthenticationCommand;
import club.kynb.mall.application.model.model.event.AuthFailedEvent;
import club.kynb.mall.user.model.dto.UserDTO;
import cn.hutool.crypto.SecureUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.common.web.exception.Errors;
import org.pizza.event.publish.EventBus;
import org.pizza.pattern.filter.Filter;
import org.pizza.pattern.filter.FilterInvoker;
import org.pizza.util.Checker;
import org.springframework.stereotype.Component;


/**
 * @author kynb_club@163.com
 * @since 2020/12/18 1:48 下午
 * 检查密码过滤器
 */
@Slf4j
@AllArgsConstructor
@Component
public class CheckPasswordFilter implements Filter<AuthenticationContext> {

    private final EventBus eventBus;

    @Override
    public void doFilter(AuthenticationContext authenticationContext, FilterInvoker<AuthenticationContext> filterInvoker) {
        log.info("检查密码过滤器 start");
        AuthenticationCommand command = authenticationContext.getAuthenticationCommand();
        UserDTO user = authenticationContext.getUser();
        Checker.ifNotThrow(command instanceof PwdAuthenticationCommand
                , (b) -> log.error("流程配置有误，当前过滤器无法处理：{}", command.getClass().getSimpleName())
                , () -> Errors.BIZ.exception("流程配置有误，请联系开发者~"));
        PwdAuthenticationCommand pwdAuthenticationCommand = (PwdAuthenticationCommand) command;
        //比对密码
        boolean result = this.checkPwd(user, pwdAuthenticationCommand.getPassword());
        Checker.ifNotThrow(result, (r) -> {
            //发布验证失败事件
            eventBus.publishEvent(AuthFailedEvent.builder()
                    .userId(user.getId())
                    .phone(user.getPhone())
                    .clientType(command.getClientType())
                    .errorCode(MallResultCode.CODE_11006.code())
                    .build());
        }, () -> Errors.BIZ.exception(MallResultCode.CODE_11006));
        log.info("检查密码过滤器 end");
        filterInvoker.invoke(authenticationContext);
    }

    private boolean checkPwd(UserDTO user, String password) {
        return SecureUtil.md5(password + user.getSalt()).equals(user.getPassword());
    }
}
